package com.mo.modular.auth.filter;

import io.jsonwebtoken.JwtException;

import java.io.IOException;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.filter.OncePerRequestFilter;

import com.mo.common.exception.TvExceptionEnum;
import com.mo.config.properties.JwtProperties;
import com.mo.core.base.tips.ErrorTip;
import com.mo.core.util.RenderUtil;
import com.mo.modular.auth.util.JwtTokenUtil;
import com.mo.tv.service.IZlSiteService;

/**
 * 对客户端请求的jwt token验证过滤器
 *
 * @author chenxiaodong
 * @Date 2017/8/24 14:04
 */
public class AuthFilter extends OncePerRequestFilter {

	private final Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Autowired
	private JwtProperties jwtProperties;
    
    @Autowired
	private IZlSiteService zlSiteService;
    
    
    @Autowired
    StringRedisTemplate stringRedisTemplate;

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) {
			chain.doFilter(request, response);
			return;
		}
		if (request.getServletPath().indexOf("recordingLive")>0) {
			chain.doFilter(request, response);
			return;
		}
		if (request.getServletPath().indexOf("registTVAPP")>0) {
			chain.doFilter(request, response);
			return;
		}
		/*if (request.getServletPath().indexOf("hessian")>0) {
			chain.doFilter(request, response);
			return;
		}*/
		if (request.getServletPath().indexOf("swagger")>0) {
			chain.doFilter(request, response);
			return;
		}
		if (request.getServletPath().indexOf("webjars")>0) {
			chain.doFilter(request, response);
			return;
		}

		if (request.getServletPath().indexOf("v2")>0) {
			chain.doFilter(request, response);
			return;
		}
		if (request.getServletPath().indexOf("api-docs")>0) {
			chain.doFilter(request, response);
			return;
		}
		
		
//		swagger-ui.html
		final String requestHeader = request.getHeader(jwtProperties
				.getHeader());
		String authToken = null;
		if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
			authToken = requestHeader.substring(7);
			// 验证token是否过期
			try {
				boolean flag = jwtTokenUtil.isTokenExpired(authToken);
				if (flag) {
					RenderUtil.renderErrorJson(response, TvExceptionEnum.TOKEN_EXPIRED.getCode(), 
							TvExceptionEnum.TOKEN_EXPIRED.getMessage());
					return;
				}else{
					if (request.getServletPath().indexOf("hessian")>0) {
						
					}else{
						//验证是否是登录状态
						String string = stringRedisTemplate.opsForValue().get(authToken);
						if(string!=null){
							String tvId = jwtTokenUtil.getTvIdFromToken(authToken);
							Map<String, Object> result = zlSiteService.findZlSiteIdByTvId(tvId);
							request.setAttribute("siteId", result.get("siteId"));
						}else{
							logger.info("**********退出token重复使用**********");
							RenderUtil.renderErrorJson(response, TvExceptionEnum.TOKEN_REUSE.getCode(), 
									TvExceptionEnum.TOKEN_REUSE.getMessage());
							return;
						}
						
					}
				}
			} catch (JwtException e) {
				e.printStackTrace();
				// 有异常就是token解析失败
				RenderUtil.renderErrorJson(response, TvExceptionEnum.TOKEN_ERROR.getCode(),
						TvExceptionEnum.TOKEN_ERROR.getMessage());
				return;
			}
		} else {
			// header没有带Bearer字段
			RenderUtil.renderErrorJson(response, TvExceptionEnum.TOKEN_ERROR.getCode(),
					TvExceptionEnum.TOKEN_ERROR.getMessage());
			return;
		}
		chain.doFilter(request, response);
	}
}